// When an item is created or modified //
// trigger List: ContractList

/* --- trigger conditions ---

@greater(triggerOutputs()?['body/ID'], 81)
@equals(triggerOutputs()?['body/FlowStatus'], 'Submit')

--- trigger conditions --- */


// 表服务
var List_ContractList = {}
var List_ApprovalData = {}
var List_Approver = {}
var List_Department = {}
var List_OtherServicesDepartment = {}


/* --- 初始化变量 --- */

var Get_item = List_ContractList.getItem(id=triggerOutputs()['body/ID'])

var Get_items_3 = List_ApprovalData.getItems(`ContractId eq ${triggerOutputs()['body/ID']}`)

var Round = float(triggerOutputs()['body/ApprovalBatch'])

var 品牌 = triggerOutputs()['Maison Value']

var 需审批的部门 = []

var 已审批的部门 = []

var ApprovealUser = []

var ApprovealUserEmail = []

// 初始化变量-ApproverUserEmail (第一批审批人)
var ApproverUserEmail = []

var AllApprover = []

var Contract_Type = triggerOutputs()['body/Contract Type Value']

var 申请人Claims = triggerOutputs()['body/Applicant/Claims']

var DepartmentHead = ''

var tableDepartment = []

var 当前审批节点 = ''

/* --- 初始化变量 --- */


// 如果是第二次提交
if(length(Get_items_3['body/value']) > 1)
{

}
else{
    return;
}


var Get_Approver_2 = List_Approver.getItems()

var Get_items_2 = List_Department.getItems(`MaisonCode eq '${品牌}'`)

// 从departmentApproval获取当前品牌的审批人，依据品牌等字段获取唯一值
var Get_items_OtherServicesDepartment_2 = List_OtherServicesDepartment.getItems(`MaisonCode eq '${品牌}'`) // Bug: 这里查询需更改

var Get_items_获取前几轮的审批记录_2 = List_ApprovalData
    .getItems(`ContractId eq ${triggerOutputs()['body/ID']} and batch_no ne ${Round} and (result eq '' or result eq null)`)

Get_items_获取前几轮的审批记录_2['body/value'].forEach(item => {
    List_ApprovalData.deleteItem(item['ID'])
})


// Get items 获取前几轮的审批记录2
var Get_items_获取前几轮的审批记录 = List_ApprovalData
    .getItems(`ContractId eq ${triggerOutputs()['body/ID']} and batch_no ne ${Round} and result ne 'Returned'`)

var 选择_27 = Get_items_获取前几轮的审批记录['body/value'].select(x => x['Position'])
已审批的部门 = 选择_27


// 合同类型为Service、Leasing或Other 2
if(Contract_Type == "Service" 
    || Contract_Type == "Other scenarios for company chop"
    || Contrac_Type == "Leasing")
{
    // ----- 获取所有需要审批的部门 2 -----

    var 选择_15 = triggerOutputs()['body/OtherDepartments'].select(x=>x['Value'])
    需审批的部门 = 选择_15

    // 涉及法务 写入Legal -Legal Backup 2
    if(triggerOutputs()['body/LegalInvolved'] == true) // Bug: str true here
    {
        需审批的部门.append("Legal")
    }

    // 涉及财务 写入三组Finance以及财务CFO 2
    if(triggerOutputs()['body/LegalInvolved'] == true) // Bug: str true here
    {
        需审批的部门.append("Finance Tax")

        // 条件 3
        if(triggerOutputs['Boutique/Office Type Value'] != "Office") // Bug: 未完善
        {
            需审批的部门.append("Finance RBO")
        }

        需审批的部门.append("Finance AP")
        需审批的部门.append('CFO Office')
    }

    需审批的部门.append("DepartmentHead")

    // 如果合同金额大于相应值，写入部门经理+1 2
    if(triggerOutputs()['body/ContractAmount'] > int(Get_items_2['body/value'][0]['MaxContractAmount']))
    {
        需审批的部门.append("SeniorDepartmentHead")
    }

    需审批的部门.append("CEO Office")
    需审批的部门.append("CEO")

    // 去除掉已经审批过的部门
    var 筛选数组_7 = 需审批的部门.where(x => !已审批的部门.contains(item))
    需审批的部门 = 筛选数组_7

    // ----- 获取所有需要审批的部门 2 -----

    // 合同类型不同时，设置数组变量为不同值 2
    if(Contract_Type == "Leasing")
    {
        tableDepartment = Get_items_2['body/value']
    }
    else
    {
        if(Contract_Type == "Other scenarios for company chop" || Contract_Type == "Service")
        {
            tableDepartment = Get_items_OtherServicesDepartment_2['body/value']
        }
    }

    // 设置ApprovalUser;生成ApprovalData占位 2
    需审批的部门.forEach(item => {
        // ----- 处理第一批审批人，需发送邮件 2 ----- 

        // 当前项为IT;Security;Digital;Procurement;Logistic 2
        if("IT;Security;Digital;Procurement;Logistic".contains(item))
        {
            // 选择-获取当前部门所有审批人的Claims 4
            var 选择_获取当前部门所有审批人的Claims_4 = tableDepartment[0][item]
                .select(x => x['Claims'])

            选择_获取当前部门所有审批人的Claims_4.forEach(claims => {
                ApprovealUser.append(item)
            })

            // 选择-获取当前部门所有审批人的Email 2
            var 选择_获取当前部门所有审批人的Email_2 = tableDepartment[0][item].select(x => x['Email']) // Bug: ??
            选择_获取当前部门所有审批人的Email_2.forEach(email => {
                ApproverUserEmail.append(email)
            })

            // 写入到Approval Data 11
            List_ApprovalData.postItem({
                "item/Title": item,
                "item/Applicant/Claims": 申请人Claims,
                "item/ContractId": triggerOutputs()['body/ID'],
                "item/Position": item,
                "item/is_completed": true,
                "item/is_validate": true,
                "item/batch_no": Round,
                "item/is_revoked": false,
                "item/is_backup": false,
                "item/AllApprover": 选择_获取当前部门所有审批人的Claims_4,
                "item/ApprovalNode": "LegalFinance"
            })
        }

        // 当前项为Legal 2
        if(item == "Legal")
        {
            var 筛选数组_5 = Get_Approver_2['body/value']
                .where(x => x['Role/Value'] == concat(item, ' ', triggerOutputs()['body/Maison Value']))
            var 选择_17 = 筛选数组_5.select(x => x['Approver']['Claims'])
            选择_17.forEach(claims => {
                ApprovealUser.append(claims)
            })

            var 选择_16 = 筛选数组_5.select(x => x['Approver']['Email'])
            选择_16.forEach(email => {
                ApproverUserEmail.append(email)
            })

            // 写入到Approval Data 12
            List_ApprovalData.postItem({
                "item/Title": item,
                "item/Applicant/Claims": 申请人Claims,
                "item/ContractId": triggerOutputs()['body/ID'],
                "item/Position": item,
                "item/is_completed": true,
                "item/is_validate": true,
                "item/batch_no": Round,
                "item/is_revoked": false,
                "item/is_backup": false,
                "item/AllApprover": 选择_17,
                "item/ApprovalNode": "LegalFinance"
            })
        }

        // 当前项为Legal Backup----- 2
        if(item == "Legal Backup")
        {
            var 筛选数组_6 = Get_Approver_2['body/value'].where(x => x['Role/Value'] == concat(item, ' ', triggerOutputs()['body/Maison Value']))
            var 选择_21 = 筛选数组_6.select(x => x['Approver']['Claims'])
            选择_21.forEach(claims => {
                ApprovealUser.append(claims)
            })

            var 选择_20 = 筛选数组_6.select(x => x['Approver']['Email'])
            选择_20.forEach(email => {
                ApproverUserEmail.append(email)
            })

            // 写入到Approval Data 14
            List_ApprovalData.postItem({
                "item/Title": item,
                "item/Applicant/Claims": 申请人Claims,
                "item/ContractId": triggerOutputs()['body/ID'],
                "item/Position": item,
                "item/is_completed": true,
                "item/is_validate": true,
                "item/batch_no": Round,
                "item/is_revoked": false,
                "item/is_backup": false,
                "item/AllApprover": 选择_21,
                "item/ApprovalNode": "LegalFinance"
            })
        }

        // 当前项为Finance AP-Tax 2
        if("Finance AP;Finance Tax".contains(item))
        {
            var Filter2_6 = Get_Approver_2['body/value'].where(x => x['Role/Value'] == item)
            var 选择_19 = Filter2_6.select(x => x['Approver']['Claims'])
            选择_19.forEach(claims => {
                ApprovealUser.append(claims)
            })

            var 选择_18 = Filter2_6.select(x => x['Approver']['Claims']) // Bug: 此处应为 Email
            选择_18.forEach(x => {
                ApproverUserEmail.append(x)
            })

            // 写入到Approval Data 13
            List_ApprovalData.postItem({
                "item/Title": item,
                "item/Applicant/Claims": 申请人Claims,
                "item/ContractId": triggerOutputs()['body/ID'],
                "item/Position": item,
                "item/is_completed": true,
                "item/is_validate": true,
                "item/batch_no": Round,
                "item/is_revoked": false,
                "item/is_backup": false,
                "item/AllApprover": 选择_19,
                "item/ApprovalNode": "LegalFinance"
            })

        }

        // 当前项为Finance RBO 2
        if(item == "Finance RBO")
        {
            var Filter2_7 = Get_Approver_2['body/value']
                .where(x => x['Role/Value'] == concat(item, ' ', triggerOutputs()['body/Maison Value']))
            var 选择_23 = Filter2_7.select(x => x['Approver']['Claims'])
            选择_23.forEach(claims => {
                ApprovealUser.append(claims)
            })

            var 选择_22 = Filter2_7.select(x => x['Approver']['Claims']) // Bug: 此处应为 Email
            选择_22.forEach(claims => {
                ApproverUserEmail.append(claims)
            })

            // 写入到Approval Data 15
            List_ApprovalData.postItem({
                "item/Title": item,
                "item/Applicant/Claims": 申请人Claims,
                "item/ContractId": triggerOutputs()['body/ID'],
                "item/Position": item,
                "item/is_completed": true,
                "item/is_validate": true,
                "item/batch_no": Round,
                "item/is_revoked": false,
                "item/is_backup": false,
                "item/AllApprover": 选择_23,
                "item/ApprovalNode": "LegalFinance"
            })
        }

        // ----- 处理第一批审批人，需发送邮件 2 ----- 

        // ----- 处理后续审批人 2 ------

        // 当前项为CFO Office 2
        if(item == "CFO Office")
        {
            var Filter2_8 = Get_Approver_2['body/value'].where(x => x['Role/Value'] == item)
            var 选择_24 = Filter2_8.select(x => x['Approver']['Claims'])

            // 写入到Approval Data 16
            List_ApprovalData.postItem({
                "item/Title": item,
                "item/Applicant/Claims": 申请人Claims,
                "item/ContractId": triggerOutputs()['body/ID'],
                "item/Position": item,
                "item/is_completed": true,
                "item/is_validate": true,
                "item/batch_no": Round,
                "item/is_revoked": false,
                "item/is_backup": false,
                "item/AllApprover": 选择_24,
                "item/ApprovalNode": "LegalFinance" // Bug： CEOOffice
            })
        }

        // 当前项为DepartmentHead 2
        if(item == "DepartmentHead")
        {
            var 选择_获取当前部门所有审批人的Claims_6 = createArray(tableDepartment[0][item]).select(x => x['Claims'])
            
            // 写入到Approval Data 20
            List_ApprovalData.postItem({
                "item/Title": "Department Head",
                "item/Applicant/Claims": 申请人Claims,
                "item/ContractId": triggerOutputs()['body/ID'],
                "item/Position": "Department Head",
                "item/is_completed": true,
                "item/is_validate": true,
                "item/batch_no": Round,
                "item/is_revoked": false,
                "item/is_backup": false,
                "item/AllApprover": 选择_获取当前部门所有审批人的Claims_6,
                "item/ApprovalNode": "DepartmentHead"
            })
        }

        // 当前项为SeniorDepartmentHead 2
        if(item == "SeniorDepartmentHead")
        {
            var 选择_获取当前部门所有审批人的Claims_5 = createArray(tableDepartment[0][item]).select(x => x['Claims'])
            // 写入到Approval Data 19
            List_ApprovalData.postItem({
                "item/Title": "Senior Department Head",
                "item/Applicant/Claims": 申请人Claims,
                "item/ContractId": triggerOutputs()['body/ID'],
                "item/Position": "Senior Department Head",
                "item/is_completed": true,
                "item/is_validate": true,
                "item/batch_no": Round,
                "item/is_revoked": false,
                "item/is_backup": false,
                "item/AllApprover": 选择_获取当前部门所有审批人的Claims_5,
                "item/ApprovalNode": "SeniorDepartmentHead"
            })
        }

        // 当前项为CEO Office 2
        if(item == "CEO Office")
        {
            var Filter2_10 = Get_Approver_2['body/value'].where(x => x['Role/Value'] == item)
            var 选择_26 = Filter2_10.select(x => x['Approver']['Claims'])
            // 写入到Approval Data 18
            List_ApprovalData.postItem({
                "item/Title": item,
                "item/Applicant/Claims": 申请人Claims,
                "item/ContractId": triggerOutputs()['body/ID'],
                "item/Position": item,
                "item/is_completed": true,
                "item/is_validate": true,
                "item/batch_no": Round,
                "item/is_revoked": false,
                "item/is_backup": false,
                "item/AllApprover": 选择_26,
                "item/ApprovalNode": "CEOOffice"
            })
        }

        // 当前项为CEO 2
        if(item == "CEO")
        {
            var Filter2_9 = Get_Approver_2['body/value'].where(x => x['Role/Value'] == item)
            var 选择_25 = Filter2_9.select(x => x['Approver']['Claims'])
            
            // 写入到Approval Data 17
            List_ApprovalData.postItem({
                "item/Title": item,
                "item/Applicant/Claims": 申请人Claims,
                "item/ContractId": triggerOutputs()['body/ID'],
                "item/Position": item,
                "item/is_completed": true,
                "item/is_validate": true,
                "item/batch_no": Round,
                "item/is_revoked": false,
                "item/is_backup": false,
                "item/AllApprover": 选择_25,
                "item/ApprovalNode": "CEO"
            })

        }

        // ----- 处理后续审批人 2 ------
    })
}

// 合同类型为Finance Stamp 2
if(Contract_Type == "Finance Stamp")
{
    // 获取所有需要审批的部门-Finance Stamp 2
    需审批的部门.append("Approver1") // Bug: should be: Approver
    需审批的部门.append("DepartmentHead")
}

// #region  此段代码不起作用

// 获取当前审批节点以及审批人
var Get_items_ApproverData_2 = List_ApprovalData.getItems(`ContractId eq '${triggerOutputs()['body/ID']}' and batch_no eq ${Round}`)
var 选择_28 = Get_items_ApproverData_2.select(x => x['ApprovalNode'])

// 条件 6
if(选择_28.contains("LegalFinance"))
{
    当前审批节点 = "LegalFinance"
    var 选择_29 = Get_items_ApproverData_2['body/value'].select(x => x['Position'])

    // 条件 10
    if(选择_29.contains("CFO Office") && length(选择_29) ==1)
    {
        // Get items-ApproverData 3
        var Get_items_ApproverData_3 = List_ApprovalData
            .getItems(`ContractId eq '${triggerOutputs()['body/ID']}' and batch_no eq ${Round} and Position eq 'CFO Office' and ApprovalNode eq 'LegalFinance'`)

        var 选择 = Get_items_ApproverData_3['AllApprover'].select(x => x['Email'])
        选择.forEach(x=> {
            ApprovealUserEmail.append(x)
        })

        Get_items_ApproverData_3['body/value'].forEach(ad => {
            var 选择_2 = ad['AllApprover'].select(x => x['Claims'])
            选择_2.forEach(x => {
                ApprovealUserEmail.append(x)
            })
        })
    }
    else{
        // 条件
        if(选择_29.contains("CFO Office") && length(body('选择_29')) > 1)
        {
            // Get items-ApproverData
            var Get_items_ApproverData = List_ApprovalData
                .getItems(`ContractId eq '${triggerOutputs()['body/ID']}' and batch_no eq ${Round} and Position ne 'CFO Office' and ApprovalNode eq 'LegalFinance'`)

            Get_items_ApproverData.forEach(ad => {
                var 选择_3 = ad['AllApprover'].select(x => x.Email)
                选择_3.forEach(x=> {
                    ApprovealUserEmail.append(x)
                })
            });

            Get_items-ApproverData['body/value'].forEach(ad => {
                var 选择_4 = ad['AllApprover'].select(x => x['Claims'])
                选择_4.forEach(x => {
                    ApprovealUserEmail.append(x)
                })
            })
        }
    }
}
else{
    // 条件 5
    if(选择_28.contains("DepartmentHead"))
    {
        当前审批节点 = "DepartmentHead"
    }
    else{
        // 条件 7
        if(选择_28.contains("SeniorDepartmentHead"))
        {
            当前审批节点 = "SeniorDepartmentHead"
        }
        else{
            // 条件 8
            if(选择_28.contains("CEOOffice"))
            {
                当前审批节点 = "CEOOffice"
            }
            else{
                // 条件 9
                if(选择_28.contains("CEO"))
                {
                    当前审批节点 = "CEO"
                }
            }
        }
    }
}

//#endregion 此段代码不起作用


// 设置ApprovalUser和ApprovedUser 2
var 设置ApprovalUser和ApprovedUser_2 = List_ContractList.update(id=triggerOutputs()['body/ID'],{
    "item/InvolveMonetary": true,
    "item/LegalInvolved": true,
    "item/ApprovalUser": ApprovealUser,
    "item/ApprovedUser": [],
    "item/ApprovalNode": "LegalFinance",
    "item/SameGroup": []
})

设置ApprovalUser和ApprovedUser_2.forEach(approver => {
    SendEmailV2(approver)
})